<template>
  <div class="h-container">
    <h3>欢迎来到.六兆年.的博客</h3>
    <div class="header-block">
      <el-avatar :size="50" :src="user.avator"></el-avatar>
      <div class="h-username">{{ user.username }}</div>
    </div>
    <div class="h-link">
      <span><el-link type="info" href="/blogs">主页</el-link></span>
      <el-divider direction="vertical"></el-divider>

      <span
        ><el-link type="success" href="/blog/add" v-if="hasLogin"
          >发表博客</el-link
        ></span
      >
      <el-divider direction="vertical" v-if="hasLogin"></el-divider>

      <span v-show="!hasLogin"
        ><el-link type="primary" href="/login">登录</el-link></span
      >
      <span v-show="hasLogin"
        ><el-link type="danger" @click="logout">退出</el-link></span
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      hasLogin: false,
      user: {
        username: "请先登录",
        avator:
          "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      },
    };
  },
  methods: {
    logout() {
      //登出后要请求接口，需要登录才能访问，要传localStorage中的token并且要删除localstorage里的token
      const _this = this;
      _this.$axios
        .get("/logout", {
          headers: {
            "Authorization": localStorage.getItem("token"),
          },
        })
        .then((res) => {
          //清除数据
          _this.$store.commit("REMOVE_INFO");
          _this.$router.push("/login");
        });
    },
  },
  created() {
    //初始查询
    if (this.$store.getters.getUser.username) {
      this.user.username = this.$store.getters.getUser.username;
      this.user.avator = this.$store.getters.getUser.avatar;
      this.hasLogin = true;
    }
  },
};
</script>

<style>
a {
  text-decoration: none;
  color: black;
}
.h-container {
  text-align: center;
  max-width: 80%;
  padding-bottom: 50px;
  margin: auto;
  margin-top: 30px;
}
.h-link {
  margin-top: 20px;
}
.h-username {
  font-family: "Times New Roman", Times, serif;
  font-size: 10px;
  font-weight: 600;
}
</style>